package com.imooc.order.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.order.VO.ResultVO;
import com.imooc.order.converter.OrderForm2OrderDTOConverter;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.form.OrderForm;
import com.imooc.order.service.OrderService;
import com.imooc.order.utils.ResultVOUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author morrow
 * @date 2019年1月1日
 * 
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	/**
	 * 1、参数校验
	 * 2、查询商品
	 * 3、计算总价
	 * 4、扣库存  (调商品服务)
	 * 5、订单入库
	 * @param orderForm
	 * @param rs
	 * @return
	 */
	@SuppressWarnings("all")
	@PostMapping("/create")
	public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult rs) {
		if (rs.hasErrors()) {
			log.error("【创建订单】参数不正确，orderForm={}", orderForm);
			throw new OrderException(ResultEnum.PARAM_ERROR.getCode(), rs.getFieldError().getDefaultMessage());
		}
		OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
		if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
			log.error("【创建订单】购物车为空");
			throw new OrderException(ResultEnum.CART_ERROR);
		}
		
		OrderDTO result = orderService.create(orderDTO);
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("orderId", result.getOrderId());
		return ResultVOUtil.success(map);
	}
	
}
